package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        //调用mapper，根据username查询，如果查不到，返回错误提示
        Employee employee = employeeMapper.findByUsername(username);
        if (employee==null){
            return ResultInfo.error("当前用户不存在");
        }
        //如果查到，将传入的password进行加密，跟查到的password做对比
        String passwordWithMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordWithMd5,employee.getPassword())){
            return ResultInfo.error("密码不正确");
        }

        //3.查看用户的status是否为0，禁用状态
        if (employee.getStatus()==Employee.STATUS_DISABLE){
            return ResultInfo.error("当前用户已经被禁用了");
        }
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);
    }

    @Override
    public void save(Employee employee) {
        //1.补齐参数
        //雪花算法
        long id = IdUtil.getSnowflake(1, 1).nextId();
        employee.setId(id);//主键
        employee.setPassword(SecureUtil.md5("123"));
        employee.setStatus(Employee.STATUS_ENABLE);

        //todo,后期优化
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
//
//        //todo 临时写死，后期要从dession中获取到当前操作用户
//        employee.setCreateUser(1L);
//        employee.setUpdateUser(1L);

        //2.调用mapper保存
        employeeMapper.save(employee);
    }

    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }

    @Override
    public void update(Employee employee) {
        //todo
        //1.设置参数
        //employee.setUpdateTime(new Date());
        //employee.setUpdateUser(1L);

        //2.调用mapper更新
        employeeMapper.update(employee);
    }
}
